package org.cocos2dx.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.content.SharedPreferences;
import java.util.UUID;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;


import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.io.FileOutputStream;

import android.provider.Settings;


import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.cocos2dx.fanpaiji.wxapi.WXEntryActivity;

import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
//import org.cocos2dx.utils.GPS.GPSLocation;
//import org.cocos2dx.utils.XinGePush.XinGePush;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;



import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.content.BroadcastReceiver;


class BatteryReceiver extends BroadcastReceiver {
    //    //获取电量信息
    public static int getBatteryQuantity() {
        return batteryLevel;
    }

    public static int batteryLevel = 0;


    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        //判断它是否是为电量变化的Broadcast Action
        if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
            //获取当前电量
            int level = intent.getIntExtra("level", 0);
            //电量的总刻度
            int scale = intent.getIntExtra("scale", 100);
            //把它转成百分比
            batteryLevel = level * 100 / scale;
            Log.d("Battery", "-------batteryLevel--" + batteryLevel);


//            Log.d("Battery", "" + intent.getIntExtra("level", 0));
//            //����������
//            Log.d("Battery", "" + intent.getIntExtra("scale", 0));
//            //��ط���
//            Log.d("Battery", "" + intent.getIntExtra("voltage", 0));
//            //����¶�
//            Log.d("Battery", "" + intent.getIntExtra("temperature", 0));

            //tv.setText("电池电量为"+((level*100)/scale)+"%");
        }
    }
}

public class NativeHelper {
    static Cocos2dxActivity mContext = null;
    static Runnable callBackRunnable = null;
    static TelephonyManager mTelephonyManager = null;
    public static BatteryReceiver batteryReceiver;

    static IntentFilter mIntentFilter;
    static int callBackRunnableCount = 0;
    protected static UUID uuid;

    public static void init(Cocos2dxActivity context) {
        mContext = context;
        mTelephonyManager = (TelephonyManager) context.getSystemService(mContext.TELEPHONY_SERVICE);

        //注册广播接受者java代码
        mIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        //创建广播接受者对象
        batteryReceiver = new BatteryReceiver();
        mContext.getBaseContext().registerReceiver(batteryReceiver, mIntentFilter);
    }

    public static void callScript(String funName, String params) {
        final String fun = funName + "(" + params + ")";
        Log.d("NativeHelper callScript", fun);
       // Cocos2dxJavascriptJavaBridge.evalString(fun);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Cocos2dxJavascriptJavaBridge.evalString(fun);
            }
        };

//       AppActivity context = AppActivity.app;
//        context.runOnGLThread(runnable);
    }

    //获取assets目录下的资源路径
    public static String getAssetPath(String relativePath) {
        String root = "res/raw-assets/resources/";
        return root + relativePath;
    }

    //获取assets目录下的资源
    public static byte[] getAssetData(String assertsPath) {
        AssetManager assetManager = mContext.getAssets();
        InputStream inputStream = null;

        try {
            inputStream = assetManager.open(assertsPath);
        } catch (IOException e) {
            Log.d("NativeHelper", "getAsserts file not exist!!");
            return null;
        }

        int fileLen = 0;
        try {
            fileLen = inputStream.available();
        } catch (IOException e) {
            Log.d("NativeHelper", "get file length error!!");
            return null;
        }

        byte[] buffer = new byte[fileLen];
        try {
            inputStream.read(buffer, 0, fileLen);
        } catch (IOException e) {
            Log.d("NativeHelper", "file buffer read error!!!");
            return null;
        }
        Log.d("NativeHelper", buffer.toString());
        return buffer;
    }
    
    public static Context getAppContext() {
        return mContext;
    }

    public static void runCallBackWithDelay(final Runnable runnable) {
        Handler handler = new Handler(mContext.getMainLooper());
        Runnable r = new Runnable() {
            @Override
            public void run() {
                mContext.runOnGLThread(runnable);
            }
        };
        handler.postDelayed(r, 1000);
    }

    public static void runCallBackWOnResume(final Runnable runnable) {
        callBackRunnable = runnable;
        callBackRunnableCount = 1;
    }

    private static String getMacAddress() {
        WifiManager wifi = (WifiManager) mContext.getApplicationContext().getSystemService(mContext.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        if (info == null)
            return "";
        return info.getMacAddress();
    }

    //获取电池电量
    public static int getBatteryStatus() {
        Log.d("zw_getBatteryStatus: ", batteryReceiver.getBatteryQuantity() + "");
//        Log.
        return batteryReceiver.getBatteryQuantity();
    }

    //获取网络状态   没有网络-5：WIFI网络0：4G网络-4：3G网络-3：2G网络-2
    public static int getNetworkStates() {
        //结果返回值

        Context context = getAppContext();
        int netType = 5;
        //获取手机所有连接管理对象
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        //NetworkInfo对象为空 则代表没有网络
        if (networkInfo == null) {
            return netType;
        }
        //否则 NetworkInfo对象不为空 则获取该networkInfo的类型
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI) {
            //WIFI
            netType = 0;
        } else if (nType == ConnectivityManager.TYPE_MOBILE) {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //3G   联通的3G为UMTS或HSDPA 电信的3G为EVDO
            if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 4;
            } else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                    || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
                    || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 3;
                //2G 移动和联通的2G为GPRS或EGDE，电信的2G为CDMA
            } else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
                    || nSubType == TelephonyManager.NETWORK_TYPE_EDGE
                    || nSubType == TelephonyManager.NETWORK_TYPE_CDMA
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 2;
            }
        }
        return netType;
    }



        public static String getUDID() {
        String udid = null;
//        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//        if (tm != null) {
//            udid = tm.getDeviceId();
//        }
       if (udid == null) {
          udid = getMacAddress();
        }
        return udid;
    }

    public static void openURL(String url) {
        Uri uri = Uri.parse(url);
        Intent it = new Intent(Intent.ACTION_VIEW, uri);
        mContext.startActivity(it);
    }

    public static void copyTextToClipBoard(String text) {
        ClipboardManager cm = (ClipboardManager)mContext.getSystemService(mContext.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", text);
        cm.setPrimaryClip(mClipData);
    }

    public static String getTextFromClipBoard() {
        ClipboardManager cm = (ClipboardManager)mContext.getSystemService(mContext.CLIPBOARD_SERVICE);
        ClipData abc = cm.getPrimaryClip();
        ClipData.Item item = abc.getItemAt(0);
        String text = item.getText().toString();
        return text;
    }

    public static void installApk(String file_path){
        File file = new File(file_path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    public static String getLocation(String listener) {
        //改用新的腾讯地图sdk
        final String _listener = listener;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
              //  GPSLocation.sendGPSRequest(_listener);
                Looper.loop();
            }
        };
        Thread locationThread = new Thread(runnable);
        locationThread.start();

        return "";
    }

    public static void  startXinGePush(String roleId) {
      //  stopXinGePush();
       // XinGePush.registerApp(roleId);
    }

    public static void stopXinGePush(){
     //   XinGePush.unregisterPush();
    }

    public static void setXinGePushTag(String tag){
    //    XinGePush.setTag(tag);
    }

    public static void removeXinGePushTag(String tag){
      //  XinGePush.delTag(tag);
    }


    /**
     * deviceID的组成为：渠道标志+识别符来源标志+hash后的终端识别符
     *
     * 渠道标志为：
     * 1，andriod（a）
     *
     * 识别符来源标志：
     * 1， wifi mac地址（wifi）；
     * 2， IMEI（imei）；
     * 3， 序列号（sn）；
     * 4， id：随机码。若前面的都取不到时，则随机生成一个随机码，需要缓存。
     *
     *
     * @return
     */
    public static String getDeviceId() {


        StringBuilder deviceId = new StringBuilder();
// 渠道标志
        deviceId.append("a");

       try {

//wifi mac地址
//            WifiManager wifi = (WifiManager) mContext.getApplicationContext().getSystemService(mContext.WIFI_SERVICE);
//            WifiInfo info = wifi.getConnectionInfo();
//            String wifiMac = info.getMacAddress();
//            if(wifiMac != null){
//                deviceId.append("wifi");
//                deviceId.append(wifiMac);
//              //  PALog.e("getDeviceId : ", deviceId.toString());
//                return deviceId.toString();
//            }

//IMEI（imei）
//            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//            String imei = tm.getDeviceId();
//            if(imei != null){
//                deviceId.append("imei");
//                deviceId.append(imei);
//              //  PALog.e("getDeviceId : ", deviceId.toString());
//                return deviceId.toString();
//            }

//序列号（sn）
//            String sn = tm.getSimSerialNumber();
//            if(sn != null){
//                deviceId.append("sn");
//                deviceId.append(sn);
//               // PALog.e("getDeviceId : ", deviceId.toString());
//                return deviceId.toString();
//            }


           // android_ID
               final String androidId = Settings.System.getString(mContext.getContentResolver(), Settings.System.ANDROID_ID);
               if (!"9774d56d682e549c".equals(androidId)) {
                   uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                   deviceId.append("ad");
                   deviceId.append(uuid);
                   return deviceId.toString();
               } else {
                   String _uuid = getUUID();
                   if(_uuid != null){
                        deviceId.append("id");
                        deviceId.append(_uuid);
                        return deviceId.toString();
                    }
               }
           } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID());
        }

        return deviceId.toString();

    }




    /**
     * 得到全局唯一UUID
     */
    public static String getUUID(){
        String uuid = null;
        SharedPreferences mShare = mContext.getSharedPreferences("sysCacheMap", Context.MODE_PRIVATE);
        //SharedPreferences mShare = getSysShare(context, "sysCacheMap");
        if(mShare != null){
            uuid = mShare.getString("uuid", "");
        }

        if(uuid == null || uuid == ""){
            uuid = UUID.randomUUID().toString();
          //  saveSysMap(mContext, "sysCacheMap", "uuid", uuid);
            SharedPreferences.Editor e = mShare.edit();
            e.putString("uuid",uuid);
            e.apply();
        }

      // PALog.e(tag, "getUUID : " + uuid);
        return uuid;
    }

    public static boolean saveImageToGallery( Bitmap bitmap, String fileName) {
        // 保存图片至指定路径
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            //发送广播通知系统图库刷新数据
            Uri uri = Uri.fromFile(file);
            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
//    public static String getSystemLanguage() {
//        return Locale.getDefault().getLanguage();
//    }
    /**
     * 获取手机厂商
     *
     * @return  手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }
    /**
     * 获取手机型号
     *
     * @return  手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }
    /**
     * 获取当前手机系统版本号
     *
     * @return  系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }


    //获取相册路径
    public static String getCameraPath() {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();

        return path;
    }
    public static void saveImageToPhotos( String pngPath, String name) {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        }

        //从路径中读取 照片
        Bitmap bmp = BitmapFactory.decodeFile(pngPath);
        Log.d("saveImageToPhotos : ", name);
        // fileName ==textureName  尽量和JS保存的一致
        String fileName = name;
        File file = new File(pngPath);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();

        }
       catch (IOException e) {
            e.printStackTrace();

        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(AppActivity.getContext().getApplicationContext().getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        }catch (IOException e) {
            e.printStackTrace();

        }
        // 最后通知图库更新
        AppActivity.getContext().getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));


    }








}
